package nio.multithread;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;


import static nio.bytebuffer.ByteBufferUtil.debugAll;



public class MultiThreadServer {
   static Logger logger = LogManager.getLogger("mylog");
    public static void main(String[] args) throws IOException {
        Selector boss = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        SelectionKey bossKey = ssc.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));

        int coreCount = Runtime.getRuntime().availableProcessors();
        Worker workers[] = new Worker[coreCount];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("work" + i);
        }
        AtomicInteger index = new AtomicInteger();
      //  Worker worker = new Worker("worker-8");
        while(true) {
            boss.select();
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            while(iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    System.out.println("conneted...{" + sc.getRemoteAddress() + "}");
                    System.out.println("before register...{" + sc.getRemoteAddress() + "}");
                    workers[index.getAndIncrement() % workers.length].register(sc);
                  //  sc.register(worker.selector, SelectionKey.OP_READ, null);
                    System.out.println("after register...{" + sc.getRemoteAddress() + "");
                }
            }
        }
    }

    static class Worker implements Runnable{
        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean start = false; //
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;
        }
        public void register(SocketChannel sc) throws IOException {
            if (!start) {
                thread = new Thread(this, name);
                thread.start();
                this.selector = Selector.open();
                start = true;
            }
            queue.add(()->{
                try{
                    this.selector.select();
                    sc.register(this.selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            selector.wakeup();
        }

        @Override
        public void run() {
            while(true) {
                try{
                   // this.selector.select();
                    Runnable task = queue.poll();
                    if (task != null) {
                        task.run();
                    }
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while(iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            logger.debug("read...{}", channel.getRemoteAddress());
                            System.out.println("read...{" + channel.getRemoteAddress() + "}");
                            channel.read(buffer);
                            buffer.flip();
                            debugAll(buffer);
                        }
                    }
                } catch(IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
